﻿using AuthenticationDemo.Common;
using AuthenticationDemo.Models.Application;
using AuthenticationDemo.Models.Base;
using AuthenticationDemo.Models.Enum;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;

namespace AuthenticationDemo.Services
{
    public class AuthService
    {
        private readonly JWTService _jwt;

        public AuthService(JWTService jwt)
        {
            _jwt = jwt;
        }
        /// <summary>
        /// JWT生成Token
        /// </summary>
        /// <param name="user"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<ResponseBase<object>> GetTemporaryToken(string user, string password)
        {
            //假设查库 用户名是admin,密码是admin999
            if (!user.Equals("admin") || !password.Equals("admin999"))
            {
                return new ResponseBase<object>
                    (
                         code: ResponseCode.BadRequest,
                         message: "用户名活密码错误",
                         success: true,
                         data: null
                    );
            }

            //生成 临时的 JWT 令牌
            var token = _jwt.GenerateUserToken(user);
            if (string.IsNullOrEmpty(token))
            {
                return new ResponseBase<object>(code: ResponseCode.OK, message: "SUCCESS", success: true, data: new
                {
                    LoginStatus = false,
                    Message = "生成Token失败",
                    Token = token,
                    ReToken = "",
                    ApplicationUser = new ApplicationUser()
                });
            }

            var applicationUser = new ApplicationUser { User = user, Role = "Admin" };
            return new ResponseBase<object>(code: ResponseCode.OK, message: "SUCCESS", success: true, data: new
            {
                LoginStatus = true,
                Message = "登录成功",
                Token = token,
                ReToken = Guid.NewGuid().ToString("N"),
                ApplicationUser = applicationUser
            });
        }

        /// <summary>
        /// 生成一个固定Token
        /// </summary>
        /// <param name="clientId"></param>
        /// <returns></returns>
        public async Task<ResponseBase<ApiFixedClientResp>> GetFixedClientToken(string clientId)
        {

            var clientList = App.Configuration.GetSection("FixedClient").Get<List<FixedClientSet>>();
            var clientData = clientList?.SingleOrDefault(it => it.ClientID.Equals(clientId));
            if (clientData == null)
            {
                return new ResponseBase<ApiFixedClientResp>(ResponseCode.BadRequest, false, "客户端ID不正确", null);
            }

            string randomStr = CommonExtend.GenerateRandomStr();
            var encryptContent = clientData.ClientID.EncryptAES().StringToBase64();
            string signature = encryptContent.Hmacsha256HashEncrypt();
            string token = $"{randomStr}.{encryptContent}.{signature}";

            await Task.CompletedTask;

            return new ResponseBase<ApiFixedClientResp>(ResponseCode.OK, true, "SUCCESS",
                new ApiFixedClientResp
                {
                    ClientID = clientId,
                    Token = token,
                });
        }
    }
}
